package cn.lokei.gateway.handler.websocket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

public class MqttMessageWebSocketFrameEncoder extends MessageToMessageEncoder<ByteBuf> {

  private Logger logger = LogManager.getLogger(this.getClass().getName());

  @Override
  protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    if (msg == null)
      return;

    // byte[] data = ;

    // out.add(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(msg)));
    ctx.channel().writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(msg)));
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    logger.info(cause);
  }
}